package com.yanwq.sayhi.controller.article.activity;

import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yanwq.sayhi.R;
import com.yanwq.sayhi.base.BaseToolbarActivity;
import com.yanwq.sayhi.common.client.OkJsonObjectResponseCallback;
import com.yanwq.sayhi.common.client.OkRequestParams;
import com.yanwq.sayhi.common.client.OkRestClient;
import com.yanwq.sayhi.common.constant.CacheConstant;
import com.yanwq.sayhi.common.constant.RegexConstant;
import com.yanwq.sayhi.common.event.ArticleEvent;
import com.yanwq.sayhi.common.tool.SharedPrefTool;
import com.yanwq.sayhi.controller.user.UserMgr;
import com.yanwq.sayhi.dao.bean.Article;
import com.yanwq.sayhi.dao.bean.Club;
import com.yanwq.sayhi.widget.MToast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

public class VideoAddActivity extends BaseToolbarActivity {

    public static final String INTENT_NAME_VIDEO_PATH = "INTENT_NAME_VIDEO_PATH";

    @BindView(R.id.tv_video_path)
    TextView mTvVideoPath;
    @BindView(R.id.vv_playback)
    VideoView mVvPlayback;
    @BindView(R.id.video_summary)
    EditText mEtSummary;

    private int mVideoCurPos;
    private String mPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_add);
        ButterKnife.bind(this);

        mPath = getIntent().getStringExtra(INTENT_NAME_VIDEO_PATH);

        if (mPath == null) {
            finish();
        }
    }

    @Override
    public void init() {

    }

    @Override
    public void initView() {
        mTvVideoPath.setText(mPath);
        mVvPlayback.setVideoPath(mPath);
        mVvPlayback.setKeepScreenOn(true);
        mVvPlayback.setMediaController(new MediaController(this));
        mVvPlayback.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
            }
        });

        mVvPlayback.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_send, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        send();
        return true;
    }

    private void send(){
        if (!Pattern.matches(RegexConstant.summary, mEtSummary.getText().toString())) {
            MToast.showShort(VideoAddActivity.this, "告诉大家你发的是什么~");
            return;
        }

        uploadPhoto();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mVvPlayback.stopPlayback();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mVvPlayback.pause();
        mVideoCurPos = mVvPlayback.getCurrentPosition();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mVvPlayback.seekTo(mVideoCurPos);
        mVvPlayback.start();
    }



    public void uploadPhoto() {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        mmr.setDataSource(mPath);
        Bitmap bitmap = mmr.getFrameAtTime(0);
        File file = new File(CacheConstant.getRootPath(), "video_cover.jpg");

        try {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        mmr.release();
        bitmap.recycle();

        OkRequestParams params = new OkRequestParams();
        params.put("mf", file.getName(), file);

        OkRestClient.getInstance().post(this, "/oss/picture", params, new OkJsonObjectResponseCallback() {
            @Override
            public void onStart() {
                showProgressDialog("上传封面");
            }

            @Override
            public void onSuccess(JSONObject jsonObject) {
                uploadVideo(jsonObject);
            }

            @Override
            public void onStop() {
            }
        });
    }

    public void uploadVideo(final JSONObject photo) {
        File file = new File(mPath);

        OkRequestParams params = new OkRequestParams();

        params.put("mf", file.getName(), file);

        OkRestClient.getInstance().post(this, "/oss/file", params, new OkJsonObjectResponseCallback() {
            @Override
            public void onStart() {
                showProgressDialog("正在上传视频");
            }

            @Override
            public void onSuccess(JSONObject jsonObject) {
                sendVideo(photo, jsonObject);
            }

            @Override
            public void onFail(int status, String s, Throwable throwable) {
                super.onFail(status, s, throwable);
                cancelProgressDialog();
            }

            @Override
            public void onStop() {
            }
        });
    }

    public void sendVideo(JSONObject photo, JSONObject video) {
        Article article = new Article();
        article.setSummary(mEtSummary.getText().toString());
        article.setPhotoThumbUrl(photo.getString("picThumbUrl"));
        article.setPhotoMediumUrl(photo.getString("picMediumUrl"));
        article.setPhotoOriginUrl(photo.getString("picOriginUrl"));
        article.setVideoUrl(video.getString("fileUrl"));
        article.setLon(0);
        article.setLat(0);
        article.setType(3);
        article.setPermission(1);

        article.setUser(UserMgr.get());

        String mPath = "/article/add";

        if (SharedPrefTool.getConfig("mode", "").equals("club")) {
            Club club = new Club();
            club.setId(SharedPrefTool.getConfig("clubId", 0));
            article.setClub(club);
            mPath = "/article/add/club";
        }

        OkRestClient.getInstance().post(this, mPath, article,
                new OkJsonObjectResponseCallback() {
                    @Override
                    public void onStart() {
                        showProgressDialog("正在发布");
                    }

                    @Override
                    public void onSuccess(JSONObject jsonObject) {
                        Article article = JSON.parseObject(jsonObject.toJSONString(),
                                Article.class);
                        MToast.showShort(VideoAddActivity.this,
                                String.format("%s 发布成功", article.getSummary()));
                        setResult(0xf1);
                        delayFinish();
                        EventBus.getDefault().post(new ArticleEvent(ArticleEvent.SEND_SUCCESS));
                    }

                    @Override
                    public void onStop() {
                        cancelProgressDialog();
                    }
                });
    }
}
